<template>
  <div>
    <el-container>
      <el-header>
        <div>
          <span>大模型驱动的《数据库》课程教学系统</span>
        </div>
        <div class="header-btns">
          <el-button type="info" @click="editTeacher">账号管理</el-button>
          <el-button type="info" @click="logout">退出</el-button>
        </div>
      </el-header>
      <!--  页面主体  -->
      <el-container>
        <!--  侧边栏    -->
        <el-aside width="isCollapse ? '64px' : '200px'">
          <div class="toggle-button" @click="toggleCollapse">|||</div>
          <!--active-text-color激活菜单文本时的颜色-->
          <!--unique-opened控制菜单展开,router使用 vue-router 的模式,激活导航时以 index 作为 path 进行路由跳转-->
          <!--侧边栏展开-->
          <el-menu background-color="#3c3f41" text-color="#fff" active-text-color="#609DBF"
                   :unique-opened="true" :collapse="isCollapse"
                   :collapse-transition="false" :router="false" :default-active="activePath" @select="handleClick">
            <!-- 一级菜单(视频教学) -->
            <el-submenu index="1">
              <template slot="title">
                <i class="el-icon-video-camera"></i>
                <span>视频教学</span>
              </template>
              <!-- 二级菜单 -->
              <el-menu-item index="1-1"><i class="el-icon-video-play"></i>视频列表</el-menu-item>
            </el-submenu>
            <!-- 一级菜单(题库管理) -->
            <el-submenu index="2" v-if="userInfo.role === 0 || userInfo.role === 1">
              <template slot="title">
                <i class="el-icon-menu"></i>
                <span>题库管理</span>
              </template>
              <!-- 二级菜单 -->
              <el-menu-item index="2-1"><i class="el-icon-chat-line-round"></i>题库编辑</el-menu-item>
            </el-submenu>
            <!-- 一级菜单(用户管理) -->
            <el-submenu index="3" v-if="userInfo.role === 0">
              <template slot="title">
                <i class="el-icon-s-order"></i>
                <span>用户管理</span>
              </template>
              <!-- 二级菜单 -->
              <el-menu-item index="3-2"><i class="el-icon-s-custom"></i>用户管理</el-menu-item>
              <el-menu-item index="3-3"><i class="el-icon-s-tools"></i>系统角色管理</el-menu-item>
              <el-menu-item index="3-1"><i class="el-icon-user-solid"></i>教师注册与删除</el-menu-item>
              <!-- <el-menu-item index="3-4"><i class="el-icon-user-solid"></i>班级注册与删除</el-menu-item> -->
              <el-menu-item index="3-5"><i class="el-icon-user-solid"></i>学生注册与删除</el-menu-item>
            </el-submenu>
            <!-- 一级菜单(教学活动管理) -->
            <el-submenu index="4">
              <template slot="title">
                <i class="el-icon-location"></i>
                <span>教学活动管理</span>
              </template>
              <!-- 二级菜单 -->
              <el-menu-item index="4-3" v-if="userInfo.role === 2"><i class="el-icon-edit-outline"></i>我的答题</el-menu-item>
              <el-menu-item index="4-2" v-if="userInfo.role === 0 || userInfo.role === 1"><i class="el-icon-s-management"></i>我的发布</el-menu-item>
            </el-submenu>
            <!-- 一级菜单(班级管理) - 对教师和管理员显示 -->
            <el-submenu index="5" v-if="userInfo.role === 0 || userInfo.role === 1">
              <template slot="title">
                <i class="el-icon-school"></i>
                <span>班级管理</span>
              </template>
              <!-- 二级菜单 -->
              <el-menu-item index="5-1">
                <i class="el-icon-reading"></i>
                <span v-if="userInfo.role === 0">所有班级</span>
                <span v-else>我的班级</span>
              </el-menu-item>
            </el-submenu>
            <!-- 数据分析与可视化 -->
            <el-submenu index="6">
              <template slot="title">
                <i class="el-icon-pie-chart"></i>
                <span>数据分析与可视化</span>
              </template>
              <!-- 二级菜单 -->
              <!-- <el-menu-item index="6-1"><i class="el-icon-data-analysis"></i>学习数据分析</el-menu-item> -->
            </el-submenu>
          </el-menu>
        </el-aside>
        <!--   右侧内容主体  -->
        <el-main>
          <!--  路由占位符-->
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
    <!-- 编辑账户信息表单 -->
    <el-dialog title="编辑账户" :visible.sync="editTeacherDialogVisible" width="50%" @close="editTeacherDialogClosed">
      <el-form :model="editTeacherForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="教师工号" prop="teacherID" disabled>
          <el-input :disabled="editTeacherForm.position !== '管理员'" v-model="editTeacherForm.teacherID" style="width: 30%"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editTeacherForm.name" style="width: 30%"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="editTeacherForm.gender" placeholder="请选择教师性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职称" disabled>
          <el-select v-model="editTeacherForm.position" placeholder="请选择教师职称">
            <el-option label="管理员" value="管理员"></el-option>
            <el-option label="教授" value="教授"></el-option>
            <el-option label="讲师" value="讲师"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="editTeacherForm.password" style="width: 30%" show-password></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="editTeacherDialogClosed">取消</el-button>
          <el-button type="primary" @click="submitEditTeacherForm">确定</el-button>
        </span>
    </el-dialog>
  </div>
</template>
<script>
import SessionManager from '../../utils/sessionManager.js'

export default {
  name: 'Manage',
  data () {
    return {
      id: null,
      // 控制菜单折叠与展开
      isCollapse: false,
      // 菜单激活项,用来在页面刷新之后仍然保持该位置被激活
      activePath: '',
      // 用户信息
      userInfo: {
        role: SessionManager.getUserRole() // 使用原始字符串类型，不进行parseInt转换
      },
      // 编辑教师
      editTeacherDialogVisible: false,
      editTeacherForm: {
        teacherID: '',
        name: '',
        gender: '',
        position: '',
        password: ''
      }
    }
  },
  created () {
    // 使用SessionManager进行调试
    SessionManager.debug();
    
    // 检查路由参数中是否有id
    if (this.$route.params.id) {
      this.id = parseInt(this.$route.params.id)
      // 确保存储到会话中
      SessionManager.setUserId(this.id);
    } else {
      // 尝试从sessionStorage中获取
      const storedId = SessionManager.getUserId();
      if (storedId) {
        this.id = parseInt(storedId)
      } else {
        console.error('用户ID不存在，请重新登录', {
          sessionKeys: Object.keys(sessionStorage),
          userID: sessionStorage.getItem('userID')
        })
        this.$message.error('用户ID不存在，请重新登录')
        this.$router.push('/')
        return
      }
    }
    
    // 初始化导航状态
    const activePath = SessionManager.getActivePath();
    if (activePath) {
      this.activePath = activePath
    } else {
      // 如果没有保存的导航状态，默认激活视频列表页面
      const defaultPath = `/manage/${this.id}/video/list`
      this.activePath = defaultPath
      SessionManager.setActivePath(defaultPath);
    }
    
    // 获取用户信息
    this.getUserInfo()
    
    // 确保最后一次记录的ID被保存到会话存储中
    if (this.id) {
      SessionManager.setUserId(this.id);
    }
  },
  methods: {
    logout () {
      SessionManager.clear();
      this.$router.push('/')
    },
    // 点击按钮切换形态
    toggleCollapse () {
      this.isCollapse = !this.isCollapse
    },
    // 保存导航状态
    saveNavState (activePath) {
      // 确保activePath有效
      if (!activePath || typeof activePath !== 'string') {
        console.error('无效的导航路径:', activePath)
        return
      }
      
      // 如果ID不存在，先检查是否在sessionStorage中
      if (!this.id) {
        const storedId = SessionManager.getUserId();
        if (storedId) {
          this.id = parseInt(storedId)
        } else {
          this.$message.error('用户ID不存在，请重新登录')
          this.$router.push('/')
          return
        }
      }
      
      SessionManager.setActivePath(activePath);
      this.activePath = activePath
    },
    // 获取用户信息
    getUserInfo () {
      // 检查用户ID是否存在
      if (!this.id) {
        // 尝试从sessionStorage获取id
        const storedId = SessionManager.getUserId();
        if (storedId) {
          this.id = parseInt(storedId)
        } else {
          console.error('无法获取用户ID，将跳转到登录页')
          this.$message.warning('用户ID不存在，将跳转至登录页')
          this.$router.push('/')
          return
        }
      }
      
      // 首先从sessionStorage获取用户角色
      const userRole = SessionManager.getUserRole();
      if (userRole) {
        // 将字符串转为数字
        this.userInfo.role = parseInt(userRole)
      }
      
      // 获取详细用户信息
      this.$http.get('/user/query', {
        params: { id: this.id || 0 }
      }).then(({ data: res }) => {
        if (res.code !== 200) {
          this.$message.error('获取用户信息失败')
        } else {
          // 合并用户角色信息，确保使用数字类型的role
          // 添加空值检查，避免读取null对象的属性
          if (res.data) {
            this.userInfo = {
              ...this.userInfo,
              ...res.data,
              role: res.data.role || this.userInfo.role
            }
          } else {
            console.warn('用户信息返回为空，使用默认信息')
          }
        }
      }).catch(error => {
        console.error('获取用户信息时发生错误:', error)
        this.$message.error('获取用户信息失败，请稍后重试')
      })
    },
    // 编辑教师信息
    editTeacher () {
      // 检查用户ID是否存在
      if (!this.id) {
        // 尝试从sessionStorage获取id
        const storedId = SessionManager.getUserId();
        if (storedId) {
          this.id = parseInt(storedId)
        } else {
          this.$message.error('用户ID不存在，请重新登录')
          return
        }
      }
      
      this.editTeacherDialogVisible = true
      this.$http.get('/user/query', {
        params: { id: this.id }
      }).then(({ data: res }) => {
        if (res.code !== 200) {
          this.$message.error('获取用户信息失败')
        } else {
          this.editTeacherForm = {
            teacherID: res.data.id,
            password: '',
            role: res.data.role
          }
        }
      })
    },
    // 关闭对话框
    editTeacherDialogClosed() {
      this.editTeacherDialogVisible = false
      this.editTeacherForm = {
        teacherID: '',
        name: '',
        gender: '',
        position: '',
        password: ''
      }
    },
    // 提交修改表单
    submitEditTeacherForm() {
      // 更新教师信息
      this.$http.post('/teacher/update', this.editTeacherForm)
        .then(({ data: res }) => {
          if (res.code === 200) {
            this.$message.success('更新成功')
            this.editTeacherDialogVisible = false
            this.getUserInfo()
          } else {
            this.$message.error(res.message || '更新失败')
          }
        })
        .catch(error => {
          console.error('更新教师信息失败', error)
          this.$message.error('更新失败')
        })
    },
    // 处理菜单项点击
    handleClick(index) {
      // 确保获取到有效的ID，避免空指针异常
      if (!this.id) {
        const storedId = SessionManager.getUserId();
        if (storedId) {
          this.id = parseInt(storedId)
        } else {
          console.error('无法获取用户ID，将跳转到登录页')
          this.$message.warning('用户ID不存在，将跳转至登录页')
          this.$router.push('/')
          return
        }
      }
      
      if (!index) {
        console.error('菜单项点击事件缺少必要参数', index)
        return
      }
      
      // 记录当前路径到会话存储
      this.saveNavState(index)
      this.activePath = index
      
      // 根据索引执行不同的路由跳转
      // 视频列表
      if (index === '1-1') {
        this.$router.push(`/manage/${this.id}/video/list`)
      }
      // 题库录入
      else if (index === '2-1') {
        this.$router.push(`/manage/${this.id}/question/add`)
      }
      // 题库编辑
      else if (index === '2-2') {
        this.$router.push(`/manage/${this.id}/question/edit`)
      }
      // 教师注册与删除
      else if (index === '3-1') {
        this.$router.push(`/manage/${this.id}/user/teacher`)
      }
      // 用户角色管理
      else if (index === '3-2') {
        this.$router.push(`/manage/${this.id}/user/roles`)
      }
      // 系统角色管理
      else if (index === '3-3') {
        this.$router.push(`/manage/${this.id}/user/system-roles`)
      }
      // 班级注册与删除
      else if (index === '3-4') {
        this.$router.push(`/manage/${this.id}/user/class`)
      }
      // 学生注册与删除
      else if (index === '3-5') {
        this.$router.push(`/manage/${this.id}/user/student`)
      }
      // 试题发布
      else if (index === '4-1') {
        this.$router.push(`/manage/${this.id}/teach/testPublish`)
      }
      // 我的答题
      else if (index === '4-3') {
        this.$router.push(`/manage/${this.id}/teach/MyAnswers`)
      }
      // 我的发布
      else if (index === '4-2') {
        this.$router.push(`/manage/${this.id}/teach/MyPublish`)
      }
      // 我的班级
      else if (index === '5-1') {
        this.$router.push(`/manage/${this.id}/class`)
      }
      // 学习数据分析
      else if (index === '6-1') {
        this.$router.push(`/manage/${this.id}/data/analysis`)
      }
    },
  }
}
</script>
<style lang="less" scoped>
.el-container{
  height: 100vh;
}
.el-header{
  background-color: #3c3f41;
  display: flex;
  justify-content: space-between;
  padding-left: 0;
  align-items: center;
  color: #fff;
  font-size: 20px;
  > div{
    display: flex;
    align-items: center;
    span{
      margin-left: 15px;
    }
  }
}
.header-btns {
  .el-button {
    margin-left: 10px;
  }
}
.el-aside{
  background-color: #3c3f41;
  height: calc(100vh - 60px);
  overflow: hidden;
  .el-menu{
    border-right: none;
    height: 100%;
  }
}
.el-main{
  background-color: #fff;
  overflow-x: hidden;
}
.toggle-button{
  background-color: #4a5064;
  font-size: 10px;
  line-height: 24px;
  color: #fff;
  text-align: center;
  letter-spacing: 0.2em; //字符之间的距离
  cursor: pointer; //鼠标以小手方式指向
}
</style>
